package com.org.zp.ctrl.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.org.base.ctrl.ActivityTaskManager;
import com.org.base.ctrl.BaseActivity;
import com.org.base.util.HttpUtils;
import com.org.base.util.HttpUtils.CallBack;
import com.org.base.widget.LoadMoreListView;
import com.org.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.org.base.widget.LoadMoreListViewWithProgress;
import com.org.zp.R;
import com.org.zp.app.RecApp;
import com.org.zp.entity.search.Position;

public class SearchJobResultActivity extends BaseActivity {
	private String keywordString = "";
	private RecApp mApp;

	private TextView headerTitle;
	private Button backbutton, top_right_btn;

	private List<Position> positions = new ArrayList<Position>();

	private LoadMoreListViewWithProgress viewWhitProgress;
	private LoadMoreListView listView;
	private LinearLayout linear;
	private PaginationAdapter adapter;

	private int currentPage;
	private int totalPage;
	private int perPageCount = 14;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				loadDataTask();
				break;
			case 1:
				adapter.notifyDataSetChanged();
				break;
			case 2:

				Toast toast2 = Toast.makeText(SearchJobResultActivity.this,
						"无反应", Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
				break;

			}
			super.handleMessage(msg);
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.position_search_result);
		mApp = (RecApp) this.getApplication();

		if (!(ActivityTaskManager.getInstance()
				.containsName("SearchJobResultActivity"))) {
			ActivityTaskManager.getInstance().putActivity(
					"SearchJobResultActivity", this);
		}

		keywordString = getIntent().getStringExtra("key");

		// 返回按钮
		backbutton = (Button) findViewById(R.id.back);
		backbutton.setText("  返回");
		backbutton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ActivityTaskManager.getInstance().removeActivity(
						"SearchJobResultActivity");
			}
		});
		// 标题
		headerTitle = (TextView) findViewById(R.id.headTitle);
		headerTitle.setText("职位列表 ");

		top_right_btn = (Button) findViewById(R.id.top_right_button);
		top_right_btn.setVisibility(View.GONE);

		init();

	}

	private void init() {

		linear = (LinearLayout) findViewById(R.id.search_job_result_linear);

		adapter = new PaginationAdapter(positions);

		viewWhitProgress = new LoadMoreListViewWithProgress(this);
		listView = viewWhitProgress.getListView();

		listView.setAdapter(adapter);
		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				loadDataTask();
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (((RecApp) getApplicationContext()).isNetWorkConnection) {

					Intent intent = new Intent(SearchJobResultActivity.this,
							PositionActivity.class);
					intent.putExtra("Job_number", positions.get(position)
							.getJob_number());
					Log.e("Job_number",
							"Job_number1 = "
									+ positions.get(position).getJob_number());
					startActivity(intent);

				} else {
					Toast toast2 = Toast.makeText(SearchJobResultActivity.this,
							"网络连接断开，请检查网络", Toast.LENGTH_SHORT);
					toast2.setGravity(Gravity.CENTER, 0, 0);
					toast2.show();
				}

			}
		});

		linear.addView(viewWhitProgress);

		Message msg0 = new Message();
		msg0.what = 0;
		handler.sendMessage(msg0);

	}

	private void loadDataTask() {

		currentPage = currentPage + 1;
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "jobslist");

		// 关键字
		if (null != keywordString && !keywordString.equals("")) {

			map.put("key", keywordString);
		}

		// 职位类别
		if (null != mApp.hPositionId.get("position_name_second")
				&& !"".equals(mApp.hPositionId.get("position_name_second")
						.toString())) {
			map.put("category", mApp.hPositionId.get("position_name_second")
					.toString());
		}

		// 行业
		if (null != mApp.hPositionId.get("position_hangye")
				&& !"".equals(mApp.hPositionId.get("position_hangye")
						.toString())) {
			map.put("trade", mApp.hPositionId.get("position_hangye").toString());
		}

		// 城市
		if (null != mApp.hPositionId.get("position_address")
				&& !"".equals(mApp.hPositionId.get("position_address")
						.toString())) {
			map.put("district", mApp.hPositionId.get("position_address")
					.toString());
		}

		// 公司规模
		if (null != mApp.hPositionId.get("position_companysize")
				&& !"".equals(mApp.hPositionId.get("position_companysize")
						.toString())) {
			map.put("scale", mApp.hPositionId.get("position_companysize")
					.toString());
		}

		// 工资范围
		if (null != mApp.hPositionId.get("position_salary")
				&& !"".equals(mApp.hPositionId.get("position_salary"))) {
			map.put("wage", mApp.hPositionId.get("position_salary").toString());
		}

		// 公司性质
		if (null != mApp.hPositionId.get("position_positiontype")
				&& !"".equals(mApp.hPositionId.get("position_positiontype")
						.toString())) {
			map.put("nature", mApp.hPositionId.get("position_positiontype")
					.toString());
		}

		map.put("currentPage", String.valueOf(currentPage));
		map.put("rowCountPerPage", perPageCount + "");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				Log.e("TMG", "result = " + response.toString());
				try {
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {

						String currentPage = response.getString("currentPage");
						String totalPage = response.getString("totalPage");

						if (currentPage.equals(totalPage)) {
							listView.loadComplete(false);
						}

						String data = response.getString("dataList");
						JSONArray list = new JSONArray(data);

						for (int i = 0; i < list.length(); i++) {
							Position info = new Position();
							JSONObject log = list.getJSONObject(i);
							info.setJob_number(log.getString("id"));
							info.setJob_city(log.getString("district_cn"));
							info.setJob_title(log.getString("jobs_name"));
							info.setCompany_name(log.getString("companyname"));
							info.setDate_opening(log.getString("refreshtime"));

							positions.add(info);
						}

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// We need notify the adapter that the data have been changed
				adapter.notifyDataSetChanged();
				viewWhitProgress.show();

			}

			@Override
			public void onFailure(Throwable e) {
				// TODO Auto-generated method stub

			}
		});

	}

	class PaginationAdapter extends BaseAdapter {
		List<Position> newsItems;

		public PaginationAdapter(List<Position> newsitems) {
			this.newsItems = newsitems;
		}

		@Override
		public int getCount() {
			return newsItems.size();
		}

		@Override
		public Object getItem(int position) {
			return newsItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			HrLetterHolder holder = null;
			if (null == view) {
				view = getLayoutInflater().inflate(
						R.layout.position_search_result_items, null);
				view.setBackgroundResource(R.drawable.list_bg_b);
				holder = new HrLetterHolder();
				holder.position_name = (TextView) view
						.findViewById(R.id.position_title);
				holder.company_name = (TextView) view
						.findViewById(R.id.com_name);
				holder.tvTitle = (TextView) view.findViewById(R.id.times_date);
				holder.tvContent = (TextView) view
						.findViewById(R.id.position_city);
				view.setTag(holder);
			} else {
				holder = (HrLetterHolder) view.getTag();
			}
			holder.position_name
					.setText(newsItems.get(position).getJob_title());
			holder.company_name.setText(newsItems.get(position)
					.getCompany_name());
			holder.tvTitle.setText(newsItems.get(position).getDate_opening());
			holder.tvContent.setText(newsItems.get(position).getJob_city());
			return view;
		}

		class HrLetterHolder {
			TextView position_name;// 职位名称
			TextView company_name;// 公司名称
			TextView tvTitle;// 日期
			TextView tvContent;// 城市

		}

		/**
		 * 添加数据列表项
		 * 
		 * @param newsitem
		 */
		public void addNewsItem(Position newsitem) {
			newsItems.add(newsitem);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ActivityTaskManager.getInstance().removeActivity(
					"SearchJobResultActivity");
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
